#include <QPoint>
#include <QRect>
#include <QPainter>

#include "wppagegraphicslistitem.h"
#include "WPData.h"
#include "themedatastorage.h"
#include "HtmlPainter.h"

WPPageGraphicsListItem::Geometry WPPageGraphicsListItem::iGeometry;

WPPageGraphicsListItem::WPPageGraphicsListItem(WPPage aPage, BusyIndicator& aBusyIndicator, ThemeData& aThemeData)
    : WPGraphicsListItem(aBusyIndicator, aThemeData)
    , iPage(aPage)
{
    setObjectName(QString::fromLatin1("WPPageListItem"));
    
    iTitle = new HtmlPainter(HtmlPainter::Content, iThemeData);
    iTitle->setContent(iPage->iTitle);
    
    //: %1 is a name and %2 is a date, e.g. by User 04/01 08:31
    iAuthorAndDate = tr("by %1 %2").arg(iPage->iWpAuthorDisplayName).arg(aPage->GetShortLocalTimeString());
}

WPPageGraphicsListItem::~WPPageGraphicsListItem()
{
    delete iTitle;
}

WPPage WPPageGraphicsListItem::GetPage() 
{
    return iPage;
}

bool WPPageGraphicsListItem::operator<(WPPageGraphicsListItem const & other)
{
    return (iPage->GetLocalTime() < other.iPage->GetLocalTime());
}

void WPPageGraphicsListItem::paintContent(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/, QWidget* /*widget*/)
{   
    painter->setPen(Qt::black);

    iTitle->setOneLineMode(iGeometry.iTitle.width());
    iTitle->paint(painter, iGeometry.iTitle);

    painter->setFont(*iThemeData.iListInfoFont);
    painter->drawText(iGeometry.iAuthorAndDate, iAuthorAndDate);
}

bool WPPageGraphicsListItem::IsBusy()
{
    return iPage->IsBusy();
}

bool WPPageGraphicsListItem::HasError()
{
	return iPage->iError;
}

void WPPageGraphicsListItem::handleGeomeryChange()
{
    iGeometry.update(*this);
    setMinimumHeight(iGeometry.height());
}

void WPPageGraphicsListItem::Geometry::update (WPPageGraphicsListItem & parent)
{
    const QSizeF size = parent.size();
    const ThemeData &theme = parent.iThemeData;
    
    if (iCachedSize == size)
        // fresh
        return;
    else
        iCachedSize = size;

    int const itemPadding = theme.iListItemInternalPadding;
    int const vPadding = theme.iListItemContentVMargin;
    int const hPadding = theme.iListItemContentHMargin;
    int const width = size.width() - 2 * hPadding;
    
    // Font metrics
    QFontMetrics infoFont (*theme.iListInfoFont);

    iTitle.setRect(hPadding, vPadding, width, parent.iTitle->fontMetrics().height());
    iAuthorAndDate.setRect(hPadding, iTitle.bottom() + itemPadding, width, infoFont.height());

    iHeight = iAuthorAndDate.bottom() + itemPadding + infoFont.height() + vPadding;
}
